package com.dbflow5.rx2;

import com.dbflow5.BaseUnitTest;
import com.dbflow5.TestDatabase;
import com.dbflow5.config.FlowManager;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.models.SimpleTestModels.SimpleModel;
import com.dbflow5.query.SQLite;
import com.dbflow5.reactivestreams.transaction.TransactionObservable;
import com.dbflow5.structure.Model;
import com.dbflow5.transaction.Transaction;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

import static org.junit.Assert.*;

public class TransactionObservablesTest extends BaseUnitTest {
    @Test
    public void testObservableRun() {
        AtomicBoolean successCalled = new AtomicBoolean(false);
        AtomicReference<List<SimpleModel>> list = new AtomicReference<>(new ArrayList<>());

        Transaction.Builder<Object> builder = FlowManager.database(TestDatabase.class, testDatabase -> null).beginTransactionAsync((Function<DatabaseWrapper, Object>) db -> {
            for(int i=0;i<10;i++) {
                Model.save(SimpleModel.class, new SimpleModel(String.valueOf(i)), db);
            }
            return null;
        });
        TransactionObservable.asSingle(builder).doAfterSuccess(o -> TransactionObservable.asSingle(FlowManager.database(TestDatabase.class, testDatabase -> null)
                .beginTransactionAsync(new Function<DatabaseWrapper, List<SimpleModel>>() {
                    @Override
                    public List<SimpleModel> apply(DatabaseWrapper db) {
                        return SQLite.select().from(SimpleModel.class).queryList(db);
                    }
                })).subscribe(loadedList -> {
                    successCalled.set(true);
                    list.set(loadedList);
                })).subscribe();

        assertTrue(successCalled.get());
        assertEquals(10, list.get().size());
    }

    @Test
    public void testMaybe() {
        final SimpleModel[] simpleModel = {new SimpleModel("")};
        TransactionObservable.asMaybe(FlowManager.database(TestDatabase.class, testDatabase -> null)
                .beginTransactionAsync((Function<DatabaseWrapper, SimpleModel>) db -> SQLite.select().from(SimpleModel.class).querySingle(db)))
                .subscribe(it -> simpleModel[0] = it);
        assertNull(simpleModel[0]);
    }
}
